import 'package:flutter/material.dart';
import 'package:opnvpn_flutter_example/data_source.dart';
import 'package:opnvpn_flutter_example/http_request.dart';

import 'package:opnvpn_flutter_example/server_config.dart';

class ServerListPage extends StatefulWidget {
  const ServerListPage({super.key});

  @override
  ServerListPageState createState() => ServerListPageState();
}

class ServerListPageState extends State<ServerListPage> {
  List<ServerConfig>? _serverConfigs; // 服务器列表

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  void _loadData() async {
    _serverConfigs = await fetchServerConfig(false);
    if (!mounted) return;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Server List'),
      ),
      body: ListView.builder(
        itemCount: _serverConfigs?.length ?? 0,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_serverConfigs?[index].serverName ?? ''),
            onTap: () {
              DataSource.setConfig(_serverConfigs![index]);
              Navigator.pop(context); // 返回选中的服务器名称
            },
          );
        },
      ),
    );
  }
}
